<script setup>
import { ref, watch } from 'vue'

const question = ref('')
const imageSrc = ref('')
const answer = ref('问题通常需要一个问号. ;-)')
const loading = ref(false)

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {
  if (newQuestion.includes('？')) {
    loading.value = true
    answer.value = '等一等...'
    try {
      const res = await fetch('https://yesno.wtf/api') //fetch()用于发送网络请求的一个javascript API
      const data = await res.json()
      answer.value = data.answer
      imageSrc.value = data.image
    } catch (error) {
      answer.value = '错误. ' + error
    } finally {
      loading.value = false
    }
  }
})
</script>

<template>
  <p>
    问一个可以用 yes或no 回答的问题:
    <input v-model="question" :disabled="loading" />
  </p>
  <p>{{ answer }}</p>
  <img :src="imageSrc" />
</template>